package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.gather.api.domain.ErpProductAtlas;
import com.erp.gather.domain.ErpProductAtlasTag;
import com.erp.gather.domain.bo.ErpProductAtlasAddBo;
import com.erp.gather.domain.bo.ErpProductAtlasBo;
import com.erp.gather.domain.vo.ErpProductAtlasVo;
import com.erp.gather.mapper.ErpProductAtlasMapper;
import com.erp.gather.mapper.ErpProductAtlasTagMapper;
import com.erp.gather.service.IErpProductAtlasService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 美工图集Service业务层处理
 *
 * @author erp
 * @date 2023-03-21
 */
@RequiredArgsConstructor
@Service
public class ErpProductAtlasServiceImpl implements IErpProductAtlasService {

    private final ErpProductAtlasMapper baseMapper;
    private final ErpProductAtlasTagMapper erpProductAtlasTagMapper;

    /**
     * 查询美工图集
     */
    @Override
    public ErpProductAtlasVo queryById(Long atlasId) {
        return baseMapper.selectVoById(atlasId);
    }

    /**
     * 查询美工图集列表
     */
    @Override
    public TableDataInfo<ErpProductAtlasVo> queryPageList(ErpProductAtlasBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpProductAtlas> lqw = buildQueryWrapper(bo);
        Page<ErpProductAtlasVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询美工图集列表
     */
    @Override
    public List<ErpProductAtlasVo> queryList(ErpProductAtlasBo bo) {
        LambdaQueryWrapper<ErpProductAtlas> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpProductAtlas> buildQueryWrapper(ErpProductAtlasBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpProductAtlas> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTagId() != null, ErpProductAtlas::getTagId, bo.getTagId());
        lqw.eq(StringUtils.isNotBlank(bo.getAtlasType()), ErpProductAtlas::getAtlasType, bo.getAtlasType());
        lqw.eq(StringUtils.isNotBlank(bo.getPictureUrl()), ErpProductAtlas::getPictureUrl, bo.getPictureUrl());
        return lqw;
    }

    /**
     * 新增美工图集
     */
    @Override
    public Boolean insertByBo(ErpProductAtlasBo bo) {
        ErpProductAtlas add = BeanUtil.toBean(bo, ErpProductAtlas.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setAtlasId(add.getAtlasId());
        }
        return flag;
    }

    /**
     * 修改美工图集
     */
    @Override
    public Boolean updateByBo(ErpProductAtlasBo bo) {
        ErpProductAtlas update = BeanUtil.toBean(bo, ErpProductAtlas.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpProductAtlas entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除美工图集
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Async
    @Override
    public void addProductAtlas(ErpProductAtlasAddBo bo) {

        //循环标签列表
        List<ErpProductAtlas> erpProductAtlasList = new ArrayList<>();
        ErpProductAtlasTag erpProductAtlasTag = new ErpProductAtlasTag();
        ErpProductAtlas atlas = new ErpProductAtlas();
        for (Long tagId : bo.getTagList()) {
            erpProductAtlasTag = erpProductAtlasTagMapper.selectOne(new LambdaQueryWrapper<ErpProductAtlasTag>().eq(ErpProductAtlasTag::getAtlasTagId, tagId));
            erpProductAtlasTag.setPictureNumber(erpProductAtlasTag.getPictureNumber() + bo.getPictureUrlList().size());
            erpProductAtlasTagMapper.updateById(erpProductAtlasTag);
            for (String url : bo.getPictureUrlList()) {
                atlas.setTagId(tagId);
                atlas.setAtlasType(bo.getAtlasType());
                atlas.setCreateTime(new Date());
                atlas.setPictureUrl(url);
                erpProductAtlasList.add(atlas);
                atlas = new ErpProductAtlas();
            }
        }
        baseMapper.insertBatch(erpProductAtlasList);
    }

    @Override
    public Boolean deleteType2() {
        List<ErpProductAtlas> atlasList = baseMapper.selectList(new LambdaQueryWrapper<ErpProductAtlas>().gt(ErpProductAtlas::getAtlasType, 1));
        for (ErpProductAtlas atlas : atlasList) {
            Long tagId = atlas.getTagId();
            ErpProductAtlasTag erpProductAtlasTag = erpProductAtlasTagMapper.selectById(tagId);
            erpProductAtlasTag.setPictureNumber(erpProductAtlasTag.getPictureNumber() - 1);
            erpProductAtlasTagMapper.updateById(erpProductAtlasTag);
        }
        int i = baseMapper.deleteBatchIds(atlasList.stream().map(ErpProductAtlas::getAtlasId).collect(Collectors.toList()));
        return i > 0;
    }

    @Override
    public List<ErpProductAtlasVo> getErrorImage() {
        List<ErpProductAtlasVo> productOptimizeList = baseMapper.selectVoList(new LambdaQueryWrapper<>());
        List<ErpProductAtlasVo> errorOptimizeList = new ArrayList<>();
        for (ErpProductAtlasVo optimizeVo : productOptimizeList) {
            String type = optimizeVo.getAtlasType();
            String pics = optimizeVo.getPictureUrl();

            // 判断图片路径有没有http
            if (!pics.startsWith("https")) {
                pics = "https://file.pbb2c.com/" + pics;
            }
            InputStream murl = null;
            BufferedImage sourceImg = null;
            try {
                murl = new URL(pics).openStream();
                sourceImg = ImageIO.read(murl);
            } catch (IOException e) {
                optimizeVo.setAtlasType("没找到");
                errorOptimizeList.add(optimizeVo);
                continue;
            }
            int height = sourceImg.getHeight();
            int width = sourceImg.getWidth();
            int product = height * width;
            if ("0".equals(type)) { //轮播图 800 * 800
                if (product != 640000) {
                    errorOptimizeList.add(optimizeVo);
                }
            }else if ("1".equals(type)) { // 详情图 750*1000
                if (product != 750000) {
                    errorOptimizeList.add(optimizeVo);
                }
            }
        }
        List<Long> ids = errorOptimizeList.stream().map(ErpProductAtlasVo::getAtlasId).collect(Collectors.toList());
        baseMapper.deleteBatchIds(ids);
        return errorOptimizeList;
    }


    @Override
    public ErpProductAtlas queryByTagId(Long tagId){
        return baseMapper.selectOne(new LambdaQueryWrapper<ErpProductAtlas>()
                .eq(ErpProductAtlas::getTagId, tagId).last("ORDER BY RAND() LIMIT 1"));
    }
}
